package com.example.minemodule.viewmodel;

import static com.examination.mlib.constants.ClickApi.Home.click_drugstab;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.hubert.guide.NewbieGuide;
import com.app.hubert.guide.core.Controller;
import com.app.hubert.guide.listener.OnGuideChangedListener;
import com.app.hubert.guide.listener.OnLayoutInflatedListener;
import com.app.hubert.guide.listener.OnPageChangedListener;
import com.app.hubert.guide.model.GuidePage;
import com.bumptech.glide.Glide;
import com.examination.mlib.constants.ClickApi;
import com.examination.mlib.constants.KitArouterConstants;
import com.examination.mlib.constants.UserInfoConstants;
import com.example.minemodule.R;
import com.example.minemodule.Utils.MineUtils;
import com.example.minemodule.adapter.MyDoctorAdapter;
import com.example.minemodule.databinding.MyDoctorDataBinding;
import com.example.minemodule.entity.MyDoctorBean;
import com.example.minemodule.model.MyDoctorModel;
import com.example.minemodule.ui.MyDoctorActivity;
import com.example.minemodule.view.OnRecyclerItemClickListener;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yilijk.base.base.BaseViewModel;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yilijk.base.utils.ToastUtils;
import com.yilijk.base.utils.UIUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by SHICHENG
 * <p>
 * Time on
 */
public class MyDoctorViewModel extends BaseViewModel<MyDoctorModel> {
    private MyDoctorAdapter adapter;
    private List<MyDoctorBean.DataBean.MyDoctorVOListBean> doctors;
    private Context mContext;
    private ItemTouchHelper mItemTouchHelper;
    private MyDoctorDataBinding mBinding;
    int pageIndex = 1;
    int totalCount = 0;
    int totalPageCount = 0;
    boolean hasNextPage = true;
    int startP = 0;
    int endP = 0;
    public MyDoctorViewModel(@NonNull Application application) {
        super(application);
    }

    @Override
    public void createRepository() {
        repository = new MyDoctorModel();
        super.createRepository();
    }

    @Override
    protected void onCleared() {
        super.onCleared();
    }

    public void initView(){
        doctors = new ArrayList<>();
        adapter = new MyDoctorAdapter(doctors, mContext);
        mBinding.slideRv.setAdapter(adapter);
        mBinding.slideRv.setLayoutManager(new LinearLayoutManager(mContext));
    }

    public void initData(){
        LoadingUtils.getLoadingUtils(mContext).showLoading();
        getDoctorData(pageIndex,10);
    }

    public void getDoctorData(int pageIndex,int pageSize){
        getRepository().getMydoctorList(pageIndex, pageSize, new HttpCallBack<MyDoctorBean>() {
            @Override
            public void onSuccess(MyDoctorBean s, int i) {
                LoadingUtils.getLoadingUtils(mContext).dismissLoading();
                if (s.isResult() && s.getData() !=null){
                    MyDoctorBean.DataBean data = s.getData();
                    totalCount = data.getTotalCount();
                    totalPageCount = data.getTotalPageCount();
                    hasNextPage = data.isHasNextPage();
                    if (data.getTotalCount() == 0){
                        mBinding.doctorDataLl.setVisibility(View.GONE);
                        mBinding.doctorNullLl.setVisibility(View.VISIBLE);
                    }else{
                        mBinding.doctorDataLl.setVisibility(View.VISIBLE);
                        mBinding.doctorNullLl.setVisibility(View.GONE);
                        guideUI();
                    }
                    if (pageIndex == 1){
                        doctors.clear();
                    }
                    if (doctors.size() != data.getTotalCount()){
                        doctors.addAll(data.getMyDoctorVOList());
                    }
                    adapter.notifyDataSetChanged();
                }

                mBinding.smartRl.finishRefresh();
                mBinding.smartRl.finishLoadMore();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(mContext).dismissLoading();
                mBinding.smartRl.finishRefresh();
                mBinding.smartRl.finishLoadMore();
            }
        });
    }

    public void changeDoctor(int oldP,int newP,long doctorId){
        getRepository().getModifySort(oldP, newP, doctorId, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s, int i) {
                ALog.e(s);
            }

            @Override
            public void onFailure(String s, int code) {

                if (endP < startP) {
                    for (int i = endP; i < startP; i++) {
                        Collections.swap(doctors, i, i + 1);
                    }
                } else {
                    for (int i = endP; i > startP; i--) {
                        Collections.swap(doctors, i, i - 1);
                    }
                }
                adapter.notifyItemMoved(endP, startP);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.has("msg") && !TextUtils.isEmpty(jsonObject.getString("msg"))){
                        ToastUtils.make()
                                .setBgColor(mContext.getResources().getColor(R.color.color_99000000))
                                .setTextColor(mContext.getResources().getColor(R.color.white))
                                .show(jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void initListener() {
        mBinding.slideRv.addOnItemTouchListener(new OnRecyclerItemClickListener(mBinding.slideRv) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
            }

            @SuppressLint("MissingPermission")
            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                CardView cv = vh.itemView.findViewById(R.id.item_mydoctor_cv);
                cv.setCardElevation(UIUtils.dp2px(mContext,5));
                if (doctors.get(vh.getAdapterPosition()).isDrag()){
                    startP = vh.getAdapterPosition();
                    mItemTouchHelper.startDrag(vh);
                    /**震动服务*/
                    Vibrator vib = (Vibrator)mContext.getSystemService(Service.VIBRATOR_SERVICE);
                    vib.vibrate(70);
                }
                //判断被拖拽的是否是前两个，如果不是则执行拖拽
//                if (vh.getLayoutPosition() != 0 && vh.getLayoutPosition() != 1) {
//                if (vh.getLayoutPosition() != 0) {
//                mItemTouchHelper.startDrag(vh);
                //获取系统震动服务
//                    Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);//震动70毫秒
//                    vib.vibrate(70);

//                }
            }
        });
        mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {


            @Override
            public boolean isItemViewSwipeEnabled() {
                return true;
            }

            /**
             * 是否处理滑动事件 以及拖拽和滑动的方向 如果是列表类型的RecyclerView的只存在UP和DOWN，
             * 如果是网格类RecyclerView则还应该多有LEFT和RIGHT
             * @param recyclerView
             * @param viewHolder
             * @return
             */
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    final int swipeFlags = 0;
                    return makeMovementFlags(dragFlags, swipeFlags);
                } else {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                    final int swipeFlags = 0;
//                    final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
                    return makeMovementFlags(dragFlags, swipeFlags);
                }
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                //得到当拖拽的viewHolder的Position
                int fromPosition = viewHolder.getAdapterPosition();
                long doctorId = doctors.get(fromPosition).getDoctorId();
                //拿到当前拖拽到的item的viewHolder
                int toPosition = target.getAdapterPosition();
                if (fromPosition < toPosition) {
                    for (int i = fromPosition; i < toPosition; i++) {
                        Collections.swap(doctors, i, i + 1);
                    }
                } else {
                    for (int i = fromPosition; i > toPosition; i--) {
                        Collections.swap(doctors, i, i - 1);
                    }
                }

                adapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                ALog.e("onSwiped");
//                int position = viewHolder.getAdapterPosition();
//                adapter.notifyItemRemoved(position);
//                doctors.remove(position);
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            /**
             * 长按选中Item的时候开始调用
             *
             * @param viewHolder
             * @param actionState
             */
            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
//                    viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
                    mBinding.slideRv.setmVerticalMoving(true);
                    mBinding.slideRv.closeMenuNow();
                }
                super.onSelectedChanged(viewHolder, actionState);
            }

            /**
             * 手指松开的时候还原
             * @param recyclerView
             * @param viewHolder
             */
            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                CardView cv = viewHolder.itemView.findViewById(R.id.item_mydoctor_cv);
                cv.setCardElevation(0);
                endP = viewHolder.getAdapterPosition();
                super.clearView(recyclerView, viewHolder);
//                viewHolder.itemView.setBackgroundColor(0);
                for (int i = 0; i < doctors.size(); i++) {
                }
                mBinding.slideRv.setmVerticalMoving(false);
                changeDoctor(startP,endP,doctors.get(endP).getDoctorId());
            }
        });
        mItemTouchHelper.attachToRecyclerView(mBinding.slideRv);
        adapter.setAdapterItemChildClick(new MyDoctorAdapter.AdapterItemChildClick() {
            @Override
            public void click(View view, int position) {
                if (view.getId() == R.id.item_mydoctor_show_hidden){
                    if (doctors.get(position).isShow()){
                        if (doctors.get(position).isLeftShiftToast()){
                            //支持左滑 且需提示
                            ToastUtils.make().setBgColor(mContext.getResources().getColor(R.color.color_99000000))
                                    .setTextColor(mContext.getResources().getColor(R.color.white))
                                    .show("已经最后一个了，请至少保留一位医生哦~");
                            return;
                        }
                        //隐藏当前医生
                        LoadingUtils.getLoadingUtils(mContext).showLoading();
                        getRepository().hiddenDoctor(doctors.get(position).getDoctorId(), new HttpCallBack<String>() {
                            @Override
                            public void onSuccess(String s, int i) {
                                LoadingUtils.getLoadingUtils(mContext).dismissLoading();
                                pageIndex = 1;
                                getDoctorData(pageIndex,10);
                            }

                            @Override
                            public void onFailure(String s, int i) {
                                LoadingUtils.getLoadingUtils(mContext).dismissLoading();
                                if (s!=null){
                                    try {
                                        JSONObject jsonObject = new JSONObject(s);
                                        if (jsonObject.has("msg") && !TextUtils.isEmpty(jsonObject.getString("msg"))){
                                            ToastUtils.showShort(jsonObject.getString("msg"));
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
                    }else{
                        //显示当前医生
                        LoadingUtils.getLoadingUtils(mContext).showLoading();
                        getRepository().showDoctor(doctors.get(position).getDoctorId(), new HttpCallBack<String>() {
                            @Override
                            public void onSuccess(String s, int i) {
                                LoadingUtils.getLoadingUtils(mContext).dismissLoading();
                                pageIndex = 1;
                                getDoctorData(pageIndex,10);
                            }

                            @Override
                            public void onFailure(String s, int i) {
                                LoadingUtils.getLoadingUtils(mContext).dismissLoading();

                            }
                        });
                    }
                }else if (view.getId() == R.id.item_mydoctor){
                    String channel = doctors.get(position).getChannel();
                    Bundle bundle = new Bundle();
                    bundle.putString("doctorId", doctors.get(position).getDoctorId() + "");
                    bundle.putInt("selectIndex", 1);
                    if (channel.equals("general")){
                        MineUtils.push(mContext,
                                KitArouterConstants.IM_DOCTORBUNDLE,
                                KitArouterConstants.Message.DoctorStudio,
                                bundle);
                        ClickUtils.sendEvent(ClickApi.Mine.click_mydoctor1, mContext, "跳转到医生工作室");
                    }else if (channel.equals("internal")){
                        MineUtils.push(mContext,
                                KitArouterConstants.CART_DOCTORBUNDLE,
                                KitArouterConstants.Cart.Drug,
                                bundle);
                        ClickUtils.sendEvent(ClickApi.Mine.click_mydoctor2, mContext, "跳转到药品详情");
                    }else{
                        MineUtils.push(mContext,
                                KitArouterConstants.CART_DOCTORBUNDLE,
                                KitArouterConstants.Cart.Packs,
                                bundle);
                        ClickUtils.sendEvent(ClickApi.Mine.click_mydoctor3, mContext, "跳转到套餐详情");
                    }
                }
            }
        });

        mBinding.smartRl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageIndex ++ ;
                if (hasNextPage){
                    getDoctorData(pageIndex,10);
                }else{
                    ToastUtils.showShort("已经没有更多数据了");
                    mBinding.smartRl.finishLoadMore();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageIndex = 1;
                doctors.clear();
                getDoctorData(pageIndex,10);
            }
        });

    }

    public void initBind(MyDoctorActivity myDoctorActivity, MyDoctorDataBinding binding) {
        mContext = myDoctorActivity;
        mBinding = binding;
    }

    public void guideUI(){
        String string = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_passportId, "");
        String tag = "patient_mine_guide_"+string;
        if (!SharedPreferencesUtils.getInstance().getPop_Boolean(tag,false)){
            NewbieGuide.with((Activity) mContext)
                    .setLabel("homeGuide")//设置引导层标示区分不同引导层，必传！否则报错
                    .setOnGuideChangedListener(new OnGuideChangedListener() {
                        @Override
                        public void onShowed(Controller controller) {
                            ALog.e("NewbieGuide onShowed");
                            //引导层显示
                        }

                        @Override
                        public void onRemoved(Controller controller) {
                            ALog.e("NewbieGuide onRemoved");
                            //引导层消失（多页切换不会触发）
                        }
                    })
                    .setOnPageChangedListener(new OnPageChangedListener() {
                        @Override
                        public void onPageChanged(int page) {
                            ALog.e("NewbieGuide onPageChanged");
                            //引导页切换，page为当前页位置，从0开始
                        }
                    })
                    .alwaysShow(true)//是否每次都显示引导层，默认false，只显示一次
                    .addGuidePage(//添加一页引导页
                            GuidePage.newInstance()//创建一个实例
//                                .addHighLight((ImageView) guide1.findViewById(R.id.home_guide_page1_img))//添加高亮的view
//                                .addHighLight(tvBottom, HighLight.Shape.RECTANGLE)
                                    .setLayoutRes(R.layout.guide_mine_page2,R.id.mine_guide_page2_next)//设置引导页布局
                                    .setEverywhereCancelable(false)//是否点击任意地方跳转下一页或者消失引导层，默认true
                                    .setOnLayoutInflatedListener(new OnLayoutInflatedListener() {
                                        @Override
                                        public void onLayoutInflated(View view) {
                                            //引导页布局填充后回调，用于初始化
                                            Glide.with(mContext).load(R.mipmap.img_doctor_change).into((ImageView) view.findViewById(R.id.page2_mine_guide_img2));
//                                        TextView tv = view.findViewById(R.id.textView2);
//                                        tv.setText("我是动态设置的文本");
                                        }
                                    })
//                                .setEnterAnimation(enterAnimation)//进入动画
//                                .setExitAnimation(exitAnimation)//退出动画
                    )
                    .addGuidePage(
                            GuidePage.newInstance()
                                    .setLayoutRes(R.layout.guide_mine_page1, R.id.mine_guide_page2_know)//引导页布局，点击跳转下一页或者消失引导层的控件id
                                    .setEverywhereCancelable(false)//是否点击任意地方跳转下一页或者消失引导层，默认true
                                    .setOnLayoutInflatedListener(new OnLayoutInflatedListener() {
                                        @Override
                                        public void onLayoutInflated(View view) {
                                            //引导页布局填充后回调，用于初始化
                                            Glide.with(mContext).load(R.mipmap.img_doctor_hide).into((ImageView) view.findViewById(R.id.page1_mine_guide_img2));
//                                        TextView tv = view.findViewById(R.id.textView2);
//                                        tv.setText("我是动态设置的文本");
                                        }
                                    })
                    )
                    .show();//显示引导层(至少需要一页引导页才能显示)
            SharedPreferencesUtils.getInstance().savePop(tag,true);
        }
    }
}
